import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { intl, nanoid10 } from "@/utils";
import { DataGrid, Popup } from 'devextreme-react';
import { CpasIcon, LayoutB } from '~/public/cpas-ui';
import { Column, Editing, Lookup, Paging, Selection } from 'devextreme-react/data-grid';
import { getCpasIcon } from '@/utils/icon';
import './index.less';

import { conditionsColumnData, conditionStatesData } from '../conditionalQueryTableList/tableColumnData';

const AdvancedQueryPupop = React.forwardRef((props: any, ref: any) => {
    const [visible, setVisible] = useState<boolean>(false);
    const popupRef = useRef<any>(null);
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const dataGridRef = useRef<any>(null);


    const queryPupopRef = useRef<any>(null);



    const [employeesData, setEmployeesData] = useState<any[]>([]);



    const onCancel = () => {
        setEmployeesData([]);
        setVisible(false);
    }
    const onOk = async () => {
        dataGridRef.current.instance.saveEditData().then(() => {
            console.log(employeesData, '@@@');
            queryPupopRef.current?.okCallback(employeesData);
            onCancel();
        })

    }



    // 自定义方法
    useImperativeHandle(ref, () => ({
        showAdvancedQueryPupop: (propsData: any) => {
            queryPupopRef.current = propsData;
            setEmployeesData([]);
            setVisible(true);
        },
    }));

    const changeSaveData = (newData: any) => {
        const tempID = newData.guid;
        // 修改更改的值
        setEmployeesData((oldData: any) => {
            let newData = [...oldData];
            newData.forEach(item => {
                if (item.guid === tempID) {
                    return newData;
                }
                return item;
            });
            return newData;
        });
    }

    const SavedData = (e: any) => {
        if (e.changes.length) {
            const { data } = e.changes[0];
            console.log(data, '@@@');

            changeSaveData(data);
        }
    }

    const relationMenuItems = (e: any) => {
        if (!dataGridRef.current) return;
        if (e?.target == 'content' && e?.row?.rowType == 'data') {
            console.log(e, e.row?.data, '@@@');
            if (!e.items) { e.items = [] };
            const rowData: any = e.row?.data;

            const tempMenus = [
                {
                    text: "删除当前行",
                    onItemClick: () => {
                        setEmployeesData((oldData: any) => {
                            let newData = [...oldData];
                            newData = newData.filter(item => item.guid !== rowData.guid);
                            return newData;
                        });
                    },
                },
                {
                    text: "全部清空",
                    onItemClick: () => {
                        console.log(rowData, '@@@ 全部清空');
                        setEmployeesData([]);
                    },
                },
            ];
            e.items.push(...tempMenus);
        }
    };
    function leftContainer() {
        return (
            <div style={{ marginRight: "15px", height: "100%" }} >
                <div>查询条件</div>
                <DataGrid
                    className='devHeadersCenter PaperDevSortableGrid advancedQueryDataGrid'
                    ref={dataGridRef}
                    dataSource={employeesData}
                    keyExpr="guid"
                    height=" calc(100% - 20px) "
                    showBorders={true}
                    showRowLines={true}
                    showColumnLines={true}
                    rowAlternationEnabled={true}
                    onCellClick={(e) => {
                        const { rowType, data, columnIndex } = e;
                        if (rowType === 'data') {
                            // console.log(data, e, columnIndex, '@@@');
                            if (columnIndex === 0) {
                                setEmployeesData((oldData: any) => {
                                    let newData = [...oldData];
                                    newData.forEach(item => {
                                        if (data.guid === item.guid) {
                                            if (item.andorStr === '1') {
                                                item.andorStr = '0';
                                            } else {
                                                item.andorStr = '1';
                                            }
                                        }
                                    });
                                    return newData;
                                })
                            } else if (columnIndex === 1) {
                                setEmployeesData((oldData: any) => {
                                    let newData = [...oldData];
                                    newData.forEach(item => {
                                        if (data.guid === item.guid) {
                                            if (item.leftParenthesis === '1') {
                                                item.leftParenthesis = '0';
                                            } else {
                                                item.leftParenthesis = '1';
                                            }
                                        }
                                    });
                                    return newData;
                                })
                            } else if (columnIndex === 5) {
                                setEmployeesData((oldData: any) => {
                                    let newData = [...oldData];
                                    newData.forEach(item => {
                                        if (data.guid === item.guid) {
                                            if (item.rightParenthesis === '1') {
                                                item.rightParenthesis = '0';
                                            } else {
                                                item.rightParenthesis = '1';
                                            }
                                        }
                                    });
                                    return newData;
                                })
                            }
                        }

                    }}
                    selection={{ mode: 'single' }}
                    allowHeaderFiltering={false}
                    allowSorting={false}
                    onSaved={SavedData}
                    onContextMenuPreparing={relationMenuItems}

                >
                    <Paging enabled={false} />
                    <Editing
                        mode="cell"
                        allowUpdating={true}
                        allowAdding={false}
                        allowDeleting={false} />
                    <Column
                        caption="或/且"
                        dataField="andorStr"
                        allowEditing={false}
                        width={60}
                        cellRender={(e) => {
                            const { data } = e;
                            let aaaa: any = null;
                            if (data.andorStr === "0") {
                                aaaa = <CpasIcon type={'icon-huo'} fontSize={16} />;
                            } else if (data.andorStr === "1") {
                                aaaa = <CpasIcon type={'icon-Remove-svg'} fontSize={16} />;
                            }
                            return <div style={{ width: '100%', height: '24px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'red', cursor: 'pointer' }}>
                                {aaaa}
                            </div>;
                        }}
                    />
                    <Column
                        caption="左括弧"
                        dataField="leftParenthesis"
                        allowEditing={false}
                        width={70}
                        cellRender={(e) => {
                            const { data } = e;
                            let aaaa: any = null;
                            if (data.leftParenthesis === "1") {
                                aaaa = '（';
                            } else {
                                aaaa = ' ';
                            }
                            return <div style={{
                                width: '100%', height: '24px',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                color: 'red', cursor: 'pointer', fontWeight: 'bold'
                            }}>
                                {aaaa}
                            </div>;
                        }}
                    />
                    <Column dataField="conditionsName" caption="字段名称" width={120}>
                        <Lookup dataSource={conditionsColumnData} valueExpr="conditionsName" displayExpr="conditionsName" />
                    </Column>


                    <Column dataField="StateID" caption="条件" width={120}>
                        <Lookup dataSource={conditionStatesData} valueExpr="StateID" displayExpr="conditionName" />
                    </Column>
                    <Column
                        caption="值"
                        dataField="rowConditionsData"
                    />
                    <Column
                        caption="右括弧"
                        dataField="rightParenthesis"
                        width={70}
                        allowEditing={false}
                        cellRender={(e) => {
                            const { data } = e;
                            let aaaa: any = null;
                            if (data.rightParenthesis === "1") {
                                aaaa = '）';
                            } else {
                                aaaa = ' ';
                            }
                            return <div style={{
                                width: '100%', height: '24px',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                color: 'red', cursor: 'pointer', fontWeight: 'bold'
                            }}>
                                {aaaa}
                            </div>;
                        }}
                    />
                </DataGrid>
            </div>
        );
    }

    function rightContainer() {
        return (
            <div style={{ marginLeft: "15px", height: "100%" }}>
                <div>双击增加条件</div>
                <DataGrid
                    dataSource={conditionsColumnData}
                    keyExpr="keyDataString"
                    showBorders={true}
                    showColumnHeaders={false}
                    height="calc(100% - 20px)"
                    onRowDblClick={(e: any) => {
                        const { data } = e;
                        setEmployeesData((oldData: any) => {
                            let newData = [...oldData];
                            newData.push({
                                guid: nanoid10(),
                                andorStr: '1',
                                leftParenthesis: '0',
                                conditionsName: data.conditionsName,
                                StateID: data.keyDataString === 'ZY' ? 7 : 0,
                                rowConditionsData: '',
                                rightParenthesis: '0',
                                keyString: data.keyDataString,
                                sqlType: data.sqlType
                            })
                            return newData;
                        });
                    }}
                >
                    <Selection mode="single" />
                    <Column
                        dataField="conditionsName"
                    />
                </DataGrid>
            </div >
        );
    }




    return (
        <>
            <Popup
                ref={popupRef}
                visible={visible}
                title='查询条件构造器'
                width={1000}
                height={600}
                // dragOutsideBoundary={true}
                // resizeEnabled={true}
                onHiding={() => { onCancel() }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },

                ]}
                contentRender={() => (
                    <div style={{ height: '475px', width: '100%', overflow: 'hidden' }} >
                        <LayoutB
                            rowSize={["650px", "700px", "750px"]}
                            leftSlot={leftContainer()}
                            rightSlot={rightContainer()}
                        />
                    </div>
                )}
            />
        </>
    );
});

export default AdvancedQueryPupop;
